import type { Directive } from "vue";
import useMenuStore from "@/stores/modules/menu";

const permission: Directive = {
  mounted(el, binding) {
    const menuStore = useMenuStore();

    const raw = binding.value;
    let codes: string[] = [];
    let mode: "some" | "every" = "some";

    if (typeof raw === "string") {
      codes = [raw];
    } else if (Array.isArray(raw)) {
      codes = raw;
    } else if (typeof raw === "object") {
      codes = Array.isArray(raw.value) ? raw.value : [raw.value];
      mode = raw.mode || "some";
    }

    const hasPermission =
      mode === "every" ? codes.every(code => menuStore.hasPermission(code)) : codes.some(code => menuStore.hasPermission(code));

    if (!hasPermission) {
      el.parentNode?.removeChild(el);
    }
  }
};

export default permission;
